import { NextApiRequest, NextApiResponse } from "next";
import { initORM } from "../../utils/orm";
import { Author } from "../../entities/Author";

async function getAuthors(req: NextApiRequest, res: NextApiResponse) {
  const em = await initORM();
  const authors = await em.findAll(Author, {});

  res.status(200).json({ authors });
}

async function createAuthor(req: NextApiRequest, res: NextApiResponse) {
  const em = await initORM();
  const author = await em.create(Author, req.body);
  await em.persistAndFlush(author);

  res.status(200).json({ author });
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method === "GET") {
    getAuthors(req, res);
  } else if (req.method === "POST") {
    createAuthor(req, res);
  } else {
    res.status(405).json({ message: "Method not allowed" });
  }
}

// curl -X POST -H "Content-Type: application/json" -d '{"name": "John Doe"}' http://localhost:3000/api/author
// curl http://localhost:3000/api/author
// curl -X DELETE -H "Content-Type: application/json" -d '{"id": 1}' http://localhost:3000/api/author
